package com.example.visitsweb.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.visitsweb.config.AliConfig;
import com.example.visitsweb.dto.VisitsRcodeDto;
import com.example.visitsweb.entity.Verify;
import com.example.visitsweb.entity.VisitsRecord;
import com.example.visitsweb.lang.Result;
import com.example.visitsweb.mapper.VerifyMapper;
import com.example.visitsweb.mapper.VisitsRecordMapper;
import com.example.visitsweb.service.VisitsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.visitsweb.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MarkerHub
 * @since 2022-04-26
 */
@Service
@Slf4j
public class VisitsRecordServiceImpl extends ServiceImpl<VisitsRecordMapper, VisitsRecord> implements VisitsRecordService {

    @Autowired
    VisitsRecordMapper visitsRecordMapper;
    @Autowired
    VerifyMapper verifyMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public Result insetRecord(VisitsRcodeDto visitsRecordDto, MultipartFile multipartFile) {
        VisitsRecord visitsRecord = new VisitsRecord();

        String url = "";
        log.info("员工信息: [{}]", visitsRecordDto.toString());
        if (multipartFile != null) {
            MultipartFile file = multipartFile;
            log.info("文件名: [{}]", file.getOriginalFilename());
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = AliConfig.END_POINT;
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = AliConfig.ACCESS_KEY_ID;
            String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
            String bucketName = AliConfig.BUCKET_NAME;
            String folder = AliConfig.FOLDER;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
                InputStream inputStream = file.getInputStream();
                //获取文件真实名称
                String originalFilename = file.getOriginalFilename();
                //重命名，防止相同文件出现覆盖
                //生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708c 需要替换成 f4f2e1a3391a4d5a94380c9f5d27708c
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //新的文件名
                originalFilename = uuid + originalFilename;
                //2、把文件按照日期进行分类
                String datePath = new DateTime().toString("yyyy/MM/dd");
                //拼接
                originalFilename = folder + "/" + datePath + "/" + originalFilename;
                // oss实现上传文件
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
                ossClient.putObject(bucketName, originalFilename, inputStream,objectMetadata);
                // 关闭OSSClient
                ossClient.shutdown();
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;

            } catch (Exception e) {
                e.printStackTrace();

            }
        }


        try {

            if (visitsRecordDto.getCasfile().equals("") && multipartFile == null) {
                return Result.fail("案件描述或信访文件不能为空");
            }
            visitsRecord.setFile(url);
            visitsRecord.setAddress(visitsRecordDto.getAddress());
            visitsRecord.setPhone(visitsRecordDto.getPhone());
            visitsRecord.setName(visitsRecordDto.getName());
            visitsRecord.setCasfile(visitsRecordDto.getCasfile());
            String today = String.format("%tF", new Date());
            visitsRecord.setTime(today);
            String a = String.valueOf((int) (Math.random() * 10000 + 10000));
            visitsRecord.setVerifyCode(a);
            visitsRecordMapper.insert(visitsRecord);
            Verify verify = new Verify();
            verify.setPhone(visitsRecordDto.getPhone());
            verify.setVerifyCode(a);
            int insert = verifyMapper.insert(verify);
            if (insert > 0) {
                redisUtil.set(verify.getPhone(), a, 60);
            }

        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail("登记失败");
        }
        return Result.succ("登记成功");
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }

        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}

